package com.demo.controller;

import com.demo.po.Items;
import com.demo.service.ItemsService;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/items")
public class ItemsController {
    
    //对日期类型的转换
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    
    @Resource
    private ItemsService itemsService;
    
    //查询所有商品
    @RequestMapping("list")
    public String list(Model model){
        List<Items> list= itemsService.findAll();
        model.addAttribute("itemsList",list);
        return "itemsList";
    }
    
    //跳转
    @RequestMapping("edit")
    public String edit(Integer id,Model model){
        //根据id查商品
        Items items=itemsService.findById(id);
        //页面回显
        model.addAttribute("item",items);
        return "editItem";
    }
    //更新商品信息
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Items items){
        itemsService.saveOrUpdate(items);
        return "redirect:list.do";
    }
    //根据ID删除
    @RequestMapping("deleteByID")
    public String deleteByID(Integer id){
        itemsService.deleteByID(id);
        return "redirect:list.do";
    }
    //批量删除
    @RequestMapping("deleteByIds")
    public String deleteByIds(Integer[] id){
        for (Integer ids : id) {
            itemsService.deleteByID(ids);
        }
        return "redirect:list.do";
    }
}
